import 'dart:async';
import 'dart:math';
import 'dart:typed_data';

import 'package:auto_size_text/auto_size_text.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_module/beans/appkey.dart';
import 'package:flutter_module/beans/conmmonResult.dart';
import 'package:flutter_module/commom/ui.dart';
import 'package:flutter_module/event/SwitchMode1_4Event.dart';
import 'package:flutter_module/event/connect_mqtt_event.dart';
import 'package:flutter_module/event/getysy_event.dart';
import 'package:flutter_module/http/api_service.dart';
import 'package:mqtt_client/mqtt_client.dart';
import 'package:flutter_module/beans/Entity.dart';
import 'package:flutter_module/commom/application.dart';
import 'package:flutter_module/event/ProductContentEvent.dart';
import 'package:flutter_module/event/login_event.dart';
import 'package:flutter_module/mqtt/Mqtt.dart';
import 'package:flutter/material.dart';
import 'package:better_socket/better_socket.dart';
import 'package:nice_button/nice_button.dart';
import 'package:oktoast/oktoast.dart';
import '../../DemoLocalizations.dart';
// Import package
// import 'package:vibrate/vibrate.dart';
// import 'package:toggle_switch/toggle_switch.dart';

///影视、图书、音乐 TAB
class VideoBookMusicBookWidget extends StatefulWidget {
  final App_esp_ip model;

  const VideoBookMusicBookWidget({Key key, @required this.model})
      : super(key: key);
  @override
  State<StatefulWidget> createState() => VideoBookMusicBookWidgetState();
}

class VideoBookMusicBookWidgetState extends State<VideoBookMusicBookWidget>
    with SingleTickerProviderStateMixin {
  var statusText = "loading";
  bool hasysy = true;
  Mqtt demo = Mqtt.getInstance();
  String deviceType;
  String deviceName = "";

  //按钮一
  String text5 = "";
  //按钮二
  String text12 = "";

  bool is33 = false;

  bool mosiButtun = false;

  //闸刀 一秒锁
  var sendCodeBtn = true;
  //1-4路四个按钮
  var sendCodeBtn1 = false;
  var sendCodeBtn2 = false;
  var sendCodeBtn3 = false;
  var sendCodeBtn4 = false;

  var controlType = 0;
  var _colorSubscription1;
  var _colorSubscription2;
  var seconds;
  @override
  void initState() {
    super.initState();
    print(widget.model);
    print(widget.model.ysyappkey);
    if (widget.model.ysyappkey != null) {
      if (widget.model.ysyappkey.isNotEmpty) {
        if (widget.model.level > 1) {
          hasysy = true;
        } else {
          print(widget.model.fromshareuser==null);
          if (widget.model.fromshareuser==null) {
              hasysy = true;
          }else{
            hasysy = false;
          }
        }
      } else {
        hasysy = false;
      }
    } else {
      hasysy = false;
    }
//    print("hasysy is ");
//    print(hasysy.toString());
    changeUI();
    this.registerLoginEvent();
    //方法名而已
  }

  void registerLoginEvent() {
//    print("进入了一下 registerLoginEvent");
    _colorSubscription1 =
        Application.eventBus.on<ProductContentEvent>().listen((event) {
      print(event.str);
      statusText = event.str;
      switch (event.str) {
        case '关到位':
          statusText = DemoLocalizations.of(context).Closeing;
          break;
        case '开到位':
          statusText = DemoLocalizations.of(context).Driveing;
          break;
        case '运行中':
          statusText = DemoLocalizations.of(context).operation;
          break;
      }
      changeUI();
    });

    _colorSubscription2 =
        Application.eventBus.on<Switch1_4ModeEvent>().listen((event) {
      if (event.message.elementAt(5) == 0) {
        sendCodeBtn1 = true;
      } else {
        sendCodeBtn1 = false;
      }
      if (event.message.elementAt(7) == 0) {
        sendCodeBtn2 = true;
      } else {
        sendCodeBtn2 = false;
      }
      if (event.message.elementAt(9) == 0) {
        sendCodeBtn3 = true;
      } else {
        sendCodeBtn3 = false;
      }
      if (event.message.elementAt(11) == 0) {
        sendCodeBtn4 = true;
      } else {
        sendCodeBtn4 = false;
      }
      changeUI();
    });
  }

  changeUI() async {
    if (mounted) {
      setState(() {});
    }
  }

  @override
  void dispose() {
    super.dispose();
    _colorSubscription1.cancel();
    _colorSubscription2.cancel();
  }

  @override
  Widget build(BuildContext context) {
    return _tabBarItem();
  }

//  Widget _tabView() {
//    return Expanded(
//      child: TabBarView(
//        children: [
//          _tabBarItem("模式一"),
//          _tabBarItem("模式二")
//        ],
//        controller: _tabController,
//      ),
//    );
//  }

  Widget getTabViewItem(String img, String txt) {
    return Column(
      children: <Widget>[
        Expanded(
          child: Padding(
            padding: EdgeInsets.only(top: 15.0, bottom: 7.0),
            child: Image.asset(
              "assets/images/" + img,
              fit: BoxFit.contain,
            ),
          ),
        ),
        Text(txt)
      ],
    );
  }

  _tabBarItem() {

    // //检查是否支持振动
    // if (await Vibration.hasVibrator()) {
    //   Vibration.vibrate();
    // }

    String tabTxt;
    deviceType = widget.model.espType;
    switch (deviceType) {
      case "11":
        //直流平移门
        deviceName = DemoLocalizations.of(context).DCtranslation;
        tabTxt = "模式一";
        text5 = DemoLocalizations.of(context).Full;
        text12 = DemoLocalizations.of(context).Pedestrian;
        break;
      case "22":
        //直流平移门
        deviceName = DemoLocalizations.of(context).DCswing;
        tabTxt = "模式一";
        text5 = DemoLocalizations.of(context).Double;
        text12 = DemoLocalizations.of(context).Single;
        break;
      case "33":
        //平开自动门
        deviceName = DemoLocalizations.of(context).automatic;
        tabTxt = "模式一";
        text5 = DemoLocalizations.of(context).Longopen;
        text12 = DemoLocalizations.of(context).Longclosed;
        is33 = true;
        break;
      case "55":
        deviceName = DemoLocalizations.of(context).ACtranslation;
        tabTxt = "模式一";
        text5 = DemoLocalizations.of(context).Full;
        text12 = DemoLocalizations.of(context).Pedestrian;
        break;
      case "66":
        deviceName = DemoLocalizations.of(context).ACside;
        tabTxt = "模式一";
        text5 = DemoLocalizations.of(context).Double;
        text12 = DemoLocalizations.of(context).Single;
        break;
      case "77":
        deviceName = DemoLocalizations.of(context).translation;
        tabTxt = "模式一";
        text5 = DemoLocalizations.of(context).Longopen;
        text12 = DemoLocalizations.of(context).Longclosed;
        mosiButtun = true;
        break;
      case "18":
        //模式二国内版
        deviceName = DemoLocalizations.of(context).translation;
        tabTxt = "模式二";
        break;
      case "28":
        deviceName = DemoLocalizations.of(context).DCswing;
        tabTxt = "模式二";
        break;
      case "58":
        deviceName = DemoLocalizations.of(context).ACtranslation;
        tabTxt = "模式二";
        break;
      case "68":
        deviceName = DemoLocalizations.of(context).ACside;
        tabTxt = "模式二";

        break;
      case "41":
        deviceName = DemoLocalizations.of(context).inching;
        tabTxt = "模式四";
        controlType = 1;
        break;
      case "42":
        deviceName = DemoLocalizations.of(context).selflocking;
        tabTxt = "模式四";
        controlType = 2;
        break;
      case "43":
        deviceName = DemoLocalizations.of(context).interlock;
        tabTxt = "模式四";
        controlType = 3;
        break;
      default:
        //case null:
        return;
    }
//    print("ze模式"+tabTxt);
    // tabTxt = "模式二";
    if (tabTxt == "模式一") {
      return Container(
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          mainAxisAlignment: MainAxisAlignment.spaceEvenly,
          mainAxisSize: MainAxisSize.max,
          textDirection: TextDirection.ltr,
          verticalDirection: VerticalDirection.down,
          children: <Widget>[
            Container(
              alignment: Alignment.center,
              margin: EdgeInsets.fromLTRB(0.0, 10.0, 0.0, 0.0),
              child: new OutlineButton(
                borderSide: new BorderSide(color: Colors.greenAccent),
                child: new Text(
                  deviceName != "" ? deviceName : 'welcome',
                  style: new TextStyle(color: Theme.of(context).primaryColor),
                ),
              ),
            ),
            Expanded(
              child: Row(
                mainAxisAlignment: MainAxisAlignment.spaceAround,
                children: <Widget>[
                  picAndTextButton(text5, () {
                    sendByMqtt(5);
                  }),
                  picAndTextButton(text12, () {
                    sendByMqtt(12);
                  }),
                  // gradientButton(5, text5),
                  // gradientButton(12, text12),
                ],
              ),
            ),
            Container(
                alignment: Alignment.center,
                child: new FloatingActionButton.extended(
                  foregroundColor: Colors.white,
                  backgroundColor: Colors.amber,
                  label: new Text(statusText, maxLines: 1),
                )),
            Expanded(
              child: Row(
                mainAxisAlignment: MainAxisAlignment.spaceAround,
                children: <Widget>[
                  picAndTextButton(
                      DemoLocalizations.of(context).Addremotecontrol, () {
                    showDialog(
                        context: context,
                        builder: (BuildContext context) {
                          return CupertinoAlertDialog(
                            title: Text(
                              DemoLocalizations.of(context).reminder,
                              style: new TextStyle(color: Colors.red),
                            ),
                            content: SizedBox(
                              child: Text('\n' +
                                  DemoLocalizations.of(context).presscontrol),
                            ),
                            actions: <Widget>[
                              CupertinoDialogAction(
                                child:
                                    Text(DemoLocalizations.of(context).confirm),
                                onPressed: () {
                                  Navigator.pop(context);
                                },
                              ),
                            ],
                          );
                        });

                    final MqttClientPayloadBuilder builder =
                        MqttClientPayloadBuilder();
                    builder.addByte(0x48);
                    builder.addByte(0x4F);
                    builder.addByte(0x41);
                    builder.addByte(0x46);
                    builder.addByte(0x56);

                    builder.addInt(13);

                    demo.publishMessage(builder);
                  }),
                  picAndTextButton(DemoLocalizations.of(context).Removeremote,
                      () {
                    showDialog(
                        context: context,
                        builder: (BuildContext context) {
                          return CupertinoAlertDialog(
                            title: Text(
                              DemoLocalizations.of(context).reminder,
                              style: new TextStyle(color: Colors.red),
                            ),
                            content: SizedBox(
                              child: Text('\n' +
                                  DemoLocalizations.of(context)
                                      .deleteallremote),
                            ),
                            actions: <Widget>[
                              CupertinoDialogAction(
                                child:
                                    Text(DemoLocalizations.of(context).cancel),
                                onPressed: () {
                                  Navigator.pop(context);
                                },
                              ),
                              CupertinoDialogAction(
                                child:
                                    Text(DemoLocalizations.of(context).confirm),
                                onPressed: () {
                                  final MqttClientPayloadBuilder builder =
                                      MqttClientPayloadBuilder();
                                  builder.addByte(0x48);
                                  builder.addByte(0x4F);
                                  builder.addByte(0x46);
                                  builder.addByte(0x49);
                                  builder.addByte(0x56);
                                  builder.addInt(13);

                                  demo.publishMessage(builder);
                                  Navigator.pop(context);
                                },
                              ),
                            ],
                          );
                        });
                  }),
                ],
              ),
            ),
            Expanded(child: new Text(''),flex: 1,),
            Container(
              child: Visibility(
                  visible: is33,
                  maintainSize: false,
                  child: Row(
                    mainAxisAlignment: MainAxisAlignment.spaceAround,
                    children: <Widget>[
                      FlatButton(
                        disabledColor: Colors.grey.withOpacity(0.1), //按钮禁用时的颜色
                        textColor: Colors.white,
                        color: Color(0xff44c5fe),
                        splashColor: Colors.white.withOpacity(0.1),
                        shape: StadiumBorder(side: BorderSide.none),
                        onPressed: () {
                          sendMosi(4);
                        },
                        child: Text(
                          DemoLocalizations.of(context).changkai,
                        ),
                      ),
                      FlatButton(
                        disabledColor: Colors.grey.withOpacity(0.1), //按钮禁用时的颜色
                        textColor: Colors.white,
                        color: Color(0xff44c5fe),
                        splashColor: Colors.white.withOpacity(0.1),
                        shape: StadiumBorder(side: BorderSide.none),
                        onPressed: () {
                          sendMosi(5);
                        },
                        child: Text(
                          DemoLocalizations.of(context).changbi,
                        ),
                      ),
                      FlatButton(
                        disabledColor: Colors.grey.withOpacity(0.1), //按钮禁用时的颜色
                        textColor: Colors.white,
                        color: Color(0xff44c5fe),
                        splashColor: Colors.white.withOpacity(0.1),
                        shape: StadiumBorder(side: BorderSide.none),
                        onPressed: () {
                          sendMosi(6);
                        },
                        child: Text(DemoLocalizations.of(context).zidong),
                      ),
                    ],
                  )),
            ),
            Container(
                child: Container(
                    width: double.infinity,
                    // height: 90,
                    margin: EdgeInsets.fromLTRB(10.0, 10.0, 10.0,
                        30.0), // 容器的外边距,这里四个参数和web不一样，顺序是 左，上，右，下
                    child: Visibility(
                        visible: hasysy,
                        maintainSize: false,
                        child: Container(
                          height: 90,
                          child: new FloatingActionButton.extended(
                              foregroundColor: Colors.white,
                              backgroundColor: Colors.deepPurpleAccent,
                              label: new Text(
                                  DemoLocalizations.of(context).startmonitoring,
                                  maxLines: 1),
                              onPressed: () {
                                _incrementCounter();
                              }),
                        )))),
          ],
        ),
      );
    } else if (tabTxt == "模式二") {
      return Container(
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          mainAxisAlignment: MainAxisAlignment.spaceEvenly,
          mainAxisSize: MainAxisSize.max,
          textDirection: TextDirection.ltr,
          verticalDirection: VerticalDirection.down,
          children: <Widget>[
            Expanded(
              child: Row(
                mainAxisAlignment: MainAxisAlignment.spaceAround,
                children: <Widget>[
                 
                  RaisedButton(
                    shape: StadiumBorder(
                      side: BorderSide(
                        width: 2,
                        color: Colors.red,
                        // style: BorderStyle.solid,
                        style: BorderStyle.none,
                      ),
                    ),
                    color: Colors.blue[300],
                    textColor: Colors.black,
                    onPressed: () {
                      // Vibrate.vibrate();
                      
                      final MqttClientPayloadBuilder builder =
                          MqttClientPayloadBuilder();
                              //                          builder.addByte(72);
                              //                          builder.addByte(1);
                              //                          builder.addByte(10);
                              //                          builder.addByte(11);
                      builder.addByte(0x48);
                      builder.addByte(0x4F);
                      builder.addByte(0x50);
                      builder.addByte(0x45);
                      builder.addByte(0x4E);
                      builder.addInt(12);

                      demo.publishMessage(builder);
                    },
                    child: Row(
                      children: <Widget>[
                        Icon(
                          Icons.settings,
                          color: Colors.greenAccent,
                        ),
                        AutoSizeText(
                          DemoLocalizations.of(context).Opendoor,
                          style: TextStyle(
                              fontSize: 15, fontWeight: FontWeight.bold),
                        )
                      ],
                    ),
                  ),
                  FlatButton(
                    shape: StadiumBorder(
                      side: BorderSide(
                        width: 2,
                        color: Colors.red,
                        // style: BorderStyle.solid,
                        style: BorderStyle.none,
                      ),
                    ),
                    color: Colors.blue[300],
                    textColor: Colors.black,
                    onPressed: () {
  // Vibrate.vibrate();

                      final MqttClientPayloadBuilder builder =
                          MqttClientPayloadBuilder();
                      builder.addByte(0x48);
                      builder.addByte(0x4F);
                      builder.addByte(0x4C);
                      builder.addByte(0x53);
                      builder.addByte(0x45);
                      builder.addInt(13);
                      demo.publishMessage(builder);
                    },
                    child: Row(
                      children: <Widget>[
                        Icon(
                          Icons.assignment_late,
                          color: Colors.red,
                        ),
                        AutoSizeText(
                          DemoLocalizations.of(context).closedoor,
                          style: TextStyle(
                              fontSize: 15, fontWeight: FontWeight.bold),
                        )
                      ],
                    ),
                  ),
                  RaisedButton(
                    shape: StadiumBorder(
                      side: BorderSide(
                        width: 2,
                        color: Colors.red,
                        // style: BorderStyle.solid,
                        style: BorderStyle.none,
                      ),
                    ),
                    color: Colors.blue[300],
                    textColor: Colors.black,
                    onPressed: () {
  // Vibrate.vibrate();

                      final MqttClientPayloadBuilder builder =
                          MqttClientPayloadBuilder();
//                      builder.addByte(0x48);
//                      builder.addByte(0x4F);
//                      builder.addByte(0x4C);
//                      builder.addByte(0x53);
//                      builder.addByte(0x45);
//                      demo.publishMessage(builder);
                      builder.addByte(0x48);
                      builder.addByte(0x4F);
                      builder.addByte(0x50);
                      builder.addByte(0x45);
                      builder.addByte(0x4E);
                      builder.addInt(16);

                      demo.publishMessage(builder);
                    },
                    child: Row(
                      children: <Widget>[
                        Icon(
                          Icons.assignment_late,
                          color: Colors.orange,
                        ),
                        AutoSizeText(
                          DemoLocalizations.of(context).stopdoor,
                          style: TextStyle(
                              fontSize: 15, fontWeight: FontWeight.bold),
                        ),
                      ],
                    ),
                  ),
                ],
              ),
            ),
            Expanded(
              child: Row(
                crossAxisAlignment: CrossAxisAlignment.start,
                mainAxisAlignment: MainAxisAlignment.spaceEvenly,
                mainAxisSize: MainAxisSize.max,
                textDirection: TextDirection.ltr,
                verticalDirection: VerticalDirection.down,
                children: <Widget>[
                  Container(
                      child: new OutlineButton(
                    borderSide: new BorderSide(color: Colors.greenAccent),
                    child: new Text(
                      DemoLocalizations.of(context).currentState,
                      style:
                          new TextStyle(color: Theme.of(context).primaryColor),
                    ),
                  )),
                  Container(
                    //color: Color(0xFFFFFF00),
                    child: new FloatingActionButton.extended(
                      foregroundColor: Colors.white,
                      backgroundColor: Colors.amber,
                      //如果不手动设置icon和text颜色,则默认使用foregroundColor颜色
//                        icon: new CircleAvatar(
//                          backgroundImage: new AssetImage('assets/images/bottom_home.png'),
//                        ),
                      label: new Text(statusText, maxLines: 1),
                    ),
                  ),
                ],
              ),
            ),
            Container(
                width: double.infinity,
                height: 90,
                margin: EdgeInsets.fromLTRB(10.0, 10.0, 10.0, 30.0),
                child: Container(
                    width: double.infinity,
                    //color: Color(0xFF0000FF),
                    child: Visibility(
                      visible: hasysy,
                      maintainSize: false,
                      child: new FloatingActionButton.extended(
                          foregroundColor: Colors.white,
                          backgroundColor: Colors.deepPurpleAccent,
                          label: new Text(
                              DemoLocalizations.of(context).startmonitoring,
                              maxLines: 1),
                          onPressed: () {
                            _incrementCounter();
                          }),
                    ))),
          ],
        ),
      );
    } else if (tabTxt == "模式四") {
      print("object 模式四");
      return Container(
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          mainAxisAlignment: MainAxisAlignment.spaceEvenly,
          mainAxisSize: MainAxisSize.max,
          textDirection: TextDirection.ltr,
          verticalDirection: VerticalDirection.down,
          children: <Widget>[
            Expanded(
              child: Row(
                mainAxisAlignment: MainAxisAlignment.spaceAround,
                children: <Widget>[
                  new OutlineButton(
                    borderSide: new BorderSide(color: Colors.greenAccent),
                    child: new Text(
                      deviceName != "" ? deviceName : 'welcome',
                      style:
                          new TextStyle(color: Theme.of(context).primaryColor),
                    ),
                  ),
                ],
              ),
            ),
            Expanded(
              child: Row(
                mainAxisAlignment: MainAxisAlignment.spaceAround,
                children: <Widget>[
                  Expanded(
                    child: FlatButton(
                      disabledColor: Colors.grey.withOpacity(0.1), //按钮禁用时的颜色
                      disabledTextColor: Colors.white, //按钮禁用时的文本颜色
                      textColor: sendCodeBtn1
                          ? Colors.white
                          : Colors.black.withOpacity(0.2), //文本颜色
                      color: sendCodeBtn1
                          ? Color(0xff44c5fe)
                          : Colors.grey.withOpacity(0.1), //按钮的颜色
                      splashColor: sendCodeBtn1
                          ? Colors.white.withOpacity(0.1)
                          : Colors.transparent,
                      shape: StadiumBorder(side: BorderSide.none),
                      onPressed: () {
                        setState(() {
                          sendKaiguanD(5);
                        });
                      },
                      child: Text(
                        '1',
                      ),
                    ),
                  ),
                  Expanded(
                    child: FlatButton(
                      disabledColor: Colors.grey.withOpacity(0.1), //按钮禁用时的颜色
                      disabledTextColor: Colors.white, //按钮禁用时的文本颜色
                      textColor: sendCodeBtn2
                          ? Colors.white
                          : Colors.black.withOpacity(0.2), //文本颜色
                      color: sendCodeBtn2
                          ? Color(0xff44c5fe)
                          : Colors.grey.withOpacity(0.1), //按钮的颜色
                      splashColor: sendCodeBtn2
                          ? Colors.white.withOpacity(0.1)
                          : Colors.transparent,
                      shape: StadiumBorder(side: BorderSide.none),
                      onPressed: () {
                        setState(() {
                          sendKaiguanD(12);
                        });
                      },
                      child: Text(
                        '2',
                      ),
                    ),
                  ),
                  Expanded(
                    child: FlatButton(
                      disabledColor: Colors.grey.withOpacity(0.1), //按钮禁用时的颜色
                      disabledTextColor: Colors.white, //按钮禁用时的文本颜色
                      textColor: sendCodeBtn3
                          ? Colors.white
                          : Colors.black.withOpacity(0.2), //文本颜色
                      color: sendCodeBtn3
                          ? Color(0xff44c5fe)
                          : Colors.grey.withOpacity(0.1), //按钮的颜色
                      splashColor: sendCodeBtn3
                          ? Colors.white.withOpacity(0.1)
                          : Colors.transparent,
                      shape: StadiumBorder(side: BorderSide.none),
                      onPressed: () {
                        setState(() {
                          sendKaiguanD(13);
                        });
                      },
                      child: Text(
                        '3',
                      ),
                    ),
                  ),
                  Expanded(
                    child: FlatButton(
                      disabledColor: Colors.grey.withOpacity(0.1), //按钮禁用时的颜色
                      disabledTextColor: Colors.white, //按钮禁用时的文本颜色
                      textColor: sendCodeBtn4
                          ? Colors.white
                          : Colors.black.withOpacity(0.2), //文本颜色
                      color: sendCodeBtn4
                          ? Color(0xff44c5fe)
                          : Colors.grey.withOpacity(0.1), //按钮的颜色
                      splashColor: sendCodeBtn4
                          ? Colors.white.withOpacity(0.1)
                          : Colors.transparent,
                      shape: StadiumBorder(side: BorderSide.none),
                      onPressed: () {
                        setState(() {
                          sendKaiguanD(16);
                        });
                      },
                      child: Text(
                        '4',
                      ),
                    ),
                  ),
                ],
              ),
            ),
            Expanded(
                flex: 1,
                child: Container(
                    width: double.infinity,
                    child: Visibility(
                      visible: hasysy,
                      maintainSize: false,
                      child: new FloatingActionButton.extended(
                          foregroundColor: Colors.white,
                          backgroundColor: Colors.deepPurpleAccent,
                          label: new Text(
                              DemoLocalizations.of(context).startmonitoring,
                              maxLines: 1),
                          onPressed: () {
                            _incrementCounter();
                          }),
                    ))),
          ],
        ),
      );
    }
  }

  static const MethodChannel methodChannel =
      MethodChannel('com.flutter.io/video');

  String naviTitle = 'title';
  // 回调事件
  void _onEvent(Object event) {
    print('flutter video reseave');

    setState(() {
      naviTitle = event.toString();
    });
  }

  // 错误返回
  void _onError(Object error) {}

  void _incrementCounter() {
    ApiService().getNewTokenByAppkey(
        widget.model.ysyappkey, widget.model.ysyserialnumber,
        (ConmmonResult conmmonResult) async {
      if (conmmonResult != null) {
        if (conmmonResult.success) {
          Map<String, dynamic> map = {
            "EzvizAppKey": widget.model.ysyappkey,
            "AccessToken": conmmonResult.message,
            "DevSerial": widget.model.ysyserialnumber
          };
          await methodChannel.invokeMethod('video', map);
        } else {
          showToast(conmmonResult.message);
        }
      }
    });
  }

  //   static Future<void> pop({bool animated}) async {
  //   await SystemChannels.platform.invokeMethod<void>('SystemNavigator.pop', animated);
  // }

  _showTimer() {
//    print("执行倒计时");
    Timer t;
    t = Timer.periodic(Duration(milliseconds: 1000), (timer) {
      setState(() {
        this.seconds--;
      });
      if (this.seconds == 0) {
        if (t != null) {
          t.cancel();
        } //清除定时器：
        setState(() {
          sendCodeBtn = true;
        });
      }
    });
  }

  void sendKaiguanD(int i) {
    // Vibrate.vibrate();
// 
    if (!sendCodeBtn) {
      showToast(DemoLocalizations.of(context).notfrequently);
      return;
    }
    sendCodeBtn = false;

    this.seconds = 1;

    _showTimer();
    final MqttClientPayloadBuilder builder = MqttClientPayloadBuilder();
    if (controlType == 1) {
      builder.addByte(0x48);
      builder.addByte(0x4F);
      builder.addByte(0x4C);
      builder.addByte(0x53);
      builder.addByte(0x45);
      builder.addInt(i);
    } else if (controlType == 2) {
      //一直置高or置地 由机器状态决定
      builder.addByte(0x48);
      builder.addByte(0x4F);
      builder.addByte(0x4C);
      builder.addByte(0x4F);
      builder.addByte(0x47);
      builder.addInt(i);
    } else if (controlType == 3) {
      //其他的一直同上
      builder.addByte(0x48);
      builder.addByte(0x4F);
      builder.addByte(0x54);
      builder.addByte(0x48);
      builder.addByte(0x4C);
      builder.addInt(i);
    }
    demo.publishMessage(builder);
  }

  void sendMosi(var controlTypeNumer) {
    // Vibrate.vibrate();

    final MqttClientPayloadBuilder builder = MqttClientPayloadBuilder();
    builder.addByte(0x48);
    builder.addByte(0x4F);
    builder.addByte(0x53);
    builder.addByte(0x55);
    builder.addByte(0x4F);
    builder.addInt(controlTypeNumer);
    demo.publishMessage(builder);
  }
}

Widget picAndTextButton(String text, Function callback) {
  return Container(
    width: 100,
    height: 100,
    decoration: BoxDecoration(
      // color: Colors.white,
      image: DecorationImage(
          image: AssetImage('assets/images/Group.png'), fit: BoxFit.fill),
    ),
    alignment: Alignment.center,
    child: FlatButton(
      onPressed: callback,
      child: AutoSizeText(
        text,
        textAlign: TextAlign.center,
      ),
      color: Colors.transparent,
    ),
  );
}

void sendByMqtt(int io) {
  // Vibrate.vibrate();
  
  final MqttClientPayloadBuilder builder = MqttClientPayloadBuilder();
  builder.addByte(0x48);
  builder.addByte(0x4F);
  builder.addByte(0x50);
  builder.addByte(0x45);
  builder.addByte(0x4E);
  builder.addInt(io);

  Mqtt.getInstance().publishMessage(builder);
}

// 渐变色按钮
Widget gradientButton(int io, String text) {
  return Container(
//      margin: EdgeInsets.fromLTRB(20, 25, 20, 0),
    decoration: BoxDecoration(
        gradient: LinearGradient(colors: [Colors.blue, Colors.red]), // 渐变色
        borderRadius: BorderRadius.circular(15)),
    child: RaisedButton(
      shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(35)),
      color: Colors.transparent, // 设为透明色
      elevation: 0, // 正常时阴影隐藏
      highlightElevation: 1, // 点击时阴影隐藏
      onPressed: () {
        final MqttClientPayloadBuilder builder = MqttClientPayloadBuilder();
        builder.addByte(0x48);
        builder.addByte(0x4F);
        builder.addByte(0x50);
        builder.addByte(0x45);
        builder.addByte(0x4E);
        builder.addInt(io);

        Mqtt.getInstance().publishMessage(builder);
      },
      child: Container(
        alignment: Alignment.center,
        height: 50,
        child: Text(text, style: TextStyle(color: Colors.white)),
      ),
    ),
  );
}
